package com.appsindy.reserv.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.appsindy.common.AppsindyConstants;
import com.appsindy.common.action.AppsindyBaseAction;
import com.appsindy.common.bo.GlobalUser;
import com.appsindy.common.dao.GlobalUserDAO;
import com.appsindy.common.util.DateUtils;
import com.appsindy.reserv.ReservConstants;
import com.appsindy.reserv.bo.Counter;
import com.appsindy.reserv.bo.ShiftTrans;
import com.appsindy.reserv.bo.ShiftTransDt;
import com.appsindy.reserv.bo.ShiftTransDtMap;
import com.appsindy.reserv.dao.ShiftControlDAO;

public class ShiftControlAction extends AppsindyBaseAction {
	
	private ShiftControlDAO shiftControlDAO;
	private GlobalUserDAO globalUserDAO;

	private ShiftTrans shiftTrans;
	private List<ShiftTransDt> shiftTransDt;
	private int shiftNo;
	
	private String[] lineNumStr;
	private String[] transStr;
	private String[] descStr;
	private String[] dateStr;
	private String[] timeStr;
	private String[] inoutTypeStr;
	private String[] cashInStr;
	private String[] cashOutStr;
	
	private ShiftTransDt trnDt;
	
	public String execute() {
		HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
		
		String allowStatus = (String)httpSession.getAttribute("S_ALLOW_SHIFT");
		if(allowStatus == null){
			httpSession.setAttribute("S_ALLOW_SHIFT", "N");
		} else{
			ShiftTrans shiftTrxMaster = (ShiftTrans)httpSession.getAttribute("S_ALLOW_SHIFT_MASTER");
			if(shiftTrxMaster == null){
				Integer shiftTransId = (Integer)httpSession.getAttribute(AppsindyConstants.S_SHIFT_TRANS_ID);
		log.info("shiftTransId = " + shiftTransId);
				if(shiftTransId != null){
					shiftTrxMaster = getShiftControlDAO().selectShiftTransView(shiftTransId);
				}
			}
		log.info("allowStatus = " + allowStatus);
		log.info("shiftTrxMaster = " + shiftTrxMaster);
			if("Y".equals(allowStatus) && shiftTrxMaster != null){
				setShiftTrans(shiftTrxMaster);
				
				List<ShiftTransDt> shiftTrxDtList = getShiftControlDAO().selectShiftTransDetailView(shiftTrxMaster.getShiftTransId());
				if(shiftTrxDtList != null){
					setShiftTransDt(shiftTrxDtList);
				} else{
					setShiftTransDt(new ArrayList<ShiftTransDt>());
				}
				httpSession.setAttribute("S_ALLOW_SHIFT_MASTER", getShiftTrans());
			} else{
				addActionError("You cannot control shift !");
			}
		}
        return SUCCESS;
    }
	
	public String getDateTime(){
		Calendar cal = Calendar.getInstance(Locale.US);
        cal.setTime(new Date());
		String json = "{'day':'" + cal.get(Calendar.DATE) + "'"
			        + ",'month':'" + (cal.get(Calendar.MONTH)+1) + "'"
			        + ",'year':'" + cal.get(Calendar.YEAR) + "'"
			        + ",'hour':'" + cal.get(Calendar.HOUR_OF_DAY) + "'"
			        + ",'minute':'" + cal.get(Calendar.MINUTE) + "'"
			        + ",'second':'" + cal.get(Calendar.SECOND) + "'"
			        + "}";
    	setJsonModel(json);
		return JSON_RESULT;
	}
	
	public String openShift(){
    	HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
		GlobalUser user = (GlobalUser)httpSession.getAttribute(AppsindyConstants.S_USER_LOGIN);
		Counter counter = (Counter)httpSession.getAttribute(AppsindyConstants.S_COUNTER);
		Integer newShiftNum = (Integer)httpSession.getAttribute(AppsindyConstants.S_SHIFT_NUM);
		try{
			if(newShiftNum == null || newShiftNum < 1){
				throw new Exception("Cannot Open Shift, because error from generate new shift num !");
			}
			ShiftTrans st = new ShiftTrans();
			st.setUserId(user.getUserId());
			st.setOrganizationId(user.getOrganizationId());
			st.setShiftStartDatetime(new Date());
			st.setShiftEndDatetime(null);
			st.setShiftNum(newShiftNum);
			st.setShiftStatus(ReservConstants.ShiftStatusOpen);
			st.setCounterId(counter.getCounterId());
			
			getShiftControlDAO().insertShiftTrans(st);
			log.info("[Header] shiftTransId = " + st.getShiftTransId());
			
			if(st.getShiftTransId() > 0){
				ShiftTransDtMap std = new ShiftTransDtMap();
				std.setUserId(user.getUserId());
				std.setOrgId(user.getOrganizationId());
				std.setShiftTransId(st.getShiftTransId());
				std.setLineNum(1);
				byte[] utf8 = ReservConstants.BalanceForward.getBytes("UTF-8");
				std.setTransName(new String(utf8, "UTF-8"));
				std.setTransDesc(null);
				std.setTransDateTime(DateUtils.getMySqlDateTimeStr(new Date(), false));
				std.setShiftTransType(ReservConstants.GlobalTypeShiftTransType);
				std.setShiftTransTypeIn(ReservConstants.ShiftTransTypeIn);
				std.setShiftTransSource(ReservConstants.GlobalTypeShiftTransSource);
				std.setShiftTransSourceSystem(ReservConstants.ShiftTransSourceSystem);
				
				getShiftControlDAO().insertShiftTransDetail(std);
				log.info("[Detail] shiftTransDetailId = " + std.getShiftTransDtId());
			}
			
			ShiftTrans shiftTrx = getShiftControlDAO().selectShiftTransView(st.getShiftTransId());
			if(shiftTrx != null){
				setShiftTrans(shiftTrx);
			} else{
				throw new Exception("No data for ShiftTransId : " + st.getShiftTransId());
			}
			
			List<ShiftTransDt> shiftTrxDtList = getShiftControlDAO().selectShiftTransDetailView(st.getShiftTransId());
			if(shiftTrxDtList != null){
				setShiftTransDt(shiftTrxDtList);
			} else{
				setShiftTransDt(new ArrayList<ShiftTransDt>());
			}
			
			httpSession.setAttribute(AppsindyConstants.S_SHIFT_TRANS_ID, st.getShiftTransId());
		//	httpSession.setAttribute(AppsindyConstants.S_SHIFT_NUM, );
			
			httpSession.setAttribute("S_ALLOW_SHIFT", "Y");
			httpSession.setAttribute("S_ALLOW_SHIFT_MASTER", getShiftTrans());
			
		} catch(Exception e){
			httpSession.setAttribute("S_ALLOW_SHIFT", "N");
			e.printStackTrace();
		}
		
		if("RESERV".equals((String)httpSession.getAttribute("S_MENU_TYPE"))){
			return "doReserv";
    	}
		return SUCCESS;
	}
	
	public String save(){
    	HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
		GlobalUser user = (GlobalUser)httpSession.getAttribute(AppsindyConstants.S_USER_LOGIN);
		ShiftTrans shiftMaster = (ShiftTrans)httpSession.getAttribute("S_ALLOW_SHIFT_MASTER");
		
    	if(lineNumStr != null && lineNumStr.length > 0 && shiftMaster != null){
    		for(int i=0; i<lineNumStr.length; i++){
    			try{
	    			ShiftTransDtMap dt = new ShiftTransDtMap();
	    			dt.setUserId(user.getUserId());
	    			dt.setOrgId(shiftMaster.getOrganizationId());
	    			dt.setShiftTransId(shiftMaster.getShiftTransId());
	    			dt.setLineNum(Integer.parseInt(lineNumStr[i]));
	    			dt.setTransName(transStr[i]);
	    			dt.setTransDesc(descStr[i]);
	    			
	    			String dateTime = dateStr[i] + " " + timeStr[i];
	    			log.info("Line : " + lineNumStr[i] + ", inoutTypeStr = " + inoutTypeStr[i+1] + ", dateTime = " + dateTime);
	    			dt.setTransDateTime(DateUtils.getMySqlDateTimeStr(DateUtils.createDateTime(dateTime, false), false));
	    			log.info("Test :: getTransDateTime : " + dt.getTransDateTime());
	    			
	    			dt.setShiftTransType(ReservConstants.GlobalTypeShiftTransType);
	    			dt.setShiftTransTypeIn(inoutTypeStr[i+1]);
	    			
	    			if(cashInStr[i] != null && !"".equals(cashInStr[i].trim())){
	    				dt.setTransAmount(Double.parseDouble(cashInStr[i]));
	    			} else if(cashOutStr[i] != null && !"".equals(cashOutStr[i].trim())){
	    				dt.setTransAmount(Double.parseDouble(cashOutStr[i]) * -1.00d);
	    			} else{
	    				dt.setTransAmount(0.00d);
	    			}
	    			
	    			dt.setShiftTransSource(ReservConstants.GlobalTypeShiftTransSource);
	    			dt.setShiftTransSourceSystem(ReservConstants.ShiftTransSourceManual);
	    			
	    			getShiftControlDAO().insertShiftTransDtManual(dt);
	    			
	    			log.info("Save (ShiftTrn " + dt.getShiftTransId() + ") Detail : ShiftTransDtId = " + dt.getShiftTransDtId());
    			} catch(Exception e){
    				e.printStackTrace();
    			}
    		}
    	}
    	return execute();
	}
	
	public String closeShift(){
    	HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
		GlobalUser user = (GlobalUser)httpSession.getAttribute(AppsindyConstants.S_USER_LOGIN);
		ShiftTrans shiftMaster = (ShiftTrans)httpSession.getAttribute("S_ALLOW_SHIFT_MASTER");
		
		if(shiftMaster != null){
			ShiftTrans st = new ShiftTrans();
			st.setUserId(user.getUserId());
			st.setOrganizationId(user.getOrganizationId());
			st.setShiftTransId(shiftMaster.getShiftTransId());
			st.setShiftStatus(ReservConstants.ShiftStatusClose);
			
			getShiftControlDAO().closeShift(st);
			httpSession.setAttribute("S_SHIFT_CLOSED", "Y");
			addActionMessage("Close Shift Success.");
		} else{
			httpSession.setAttribute("S_SHIFT_CLOSED", "N");
			addActionError("Cannot Close Shift, No data for close shift !");
		}
		//return execute();
		return "logout";
	}
	
	public String deleteRow(){
    	HttpSession httpSession = ServletActionContext.getRequest().getSession(false);
		GlobalUser user = (GlobalUser)httpSession.getAttribute(AppsindyConstants.S_USER_LOGIN);
		ShiftTrans shiftMaster = (ShiftTrans)httpSession.getAttribute("S_ALLOW_SHIFT_MASTER");
		
		log.info("Delete row : " + trnDt.getLineNum());
		if(user != null && shiftMaster != null && trnDt.getLineNum() > 0){
			ShiftTransDtMap shftDt = new ShiftTransDtMap();
			shftDt.setUserId(user.getUserId());
			shftDt.setOrgId(user.getOrganizationId());
			shftDt.setShiftTransId(shiftMaster.getShiftTransId());
			shftDt.setShiftTransDtId(trnDt.getShiftTransDtId());
			shftDt.setLineNum(trnDt.getLineNum());
			getShiftControlDAO().deleteShiftTransDtManual(shftDt);
		}
		return execute();
	}
	
	public void setShiftControlDAO(ShiftControlDAO shiftControlDAO){
		this.shiftControlDAO = shiftControlDAO;
	}
	public ShiftControlDAO getShiftControlDAO(){
		return shiftControlDAO;
	}
	
	public void setGlobalUserDAO(GlobalUserDAO globalUserDAO){
		this.globalUserDAO = globalUserDAO;
	}
	public GlobalUserDAO getGlobalUserDAO(){
		return globalUserDAO;
	}

	public int getShiftNo() {
		return shiftNo;
	}
	public void setShiftNo(int shiftNo) {
		this.shiftNo = shiftNo;
	}

	public ShiftTrans getShiftTrans() {
		return shiftTrans;
	}
	public void setShiftTrans(ShiftTrans shiftTrans) {
		this.shiftTrans = shiftTrans;
	}
	
	public List<ShiftTransDt> getShiftTransDt() {
		return shiftTransDt;
	}
	public void setShiftTransDt(List<ShiftTransDt> shiftTransDt) {
		this.shiftTransDt = shiftTransDt;
	}
	
	// ========== Properties for add record ==========
	public String[] getTransStr() {
		return transStr;
	}
	public void setTransStr(String[] transStr) {
		this.transStr = transStr;
	}

	public String[] getDescStr() {
		return descStr;
	}
	public void setDescStr(String[] descStr) {
		this.descStr = descStr;
	}

	public String[] getDateStr() {
		return dateStr;
	}
	public void setDateStr(String[] dateStr) {
		this.dateStr = dateStr;
	}

	public String[] getTimeStr() {
		return timeStr;
	}
	public void setTimeStr(String[] timeStr) {
		this.timeStr = timeStr;
	}

	public String[] getInoutTypeStr() {
		return inoutTypeStr;
	}
	public void setInoutTypeStr(String[] inoutTypeStr) {
		this.inoutTypeStr = inoutTypeStr;
	}

	public String[] getCashInStr() {
		return cashInStr;
	}
	public void setCashInStr(String[] cashInStr) {
		this.cashInStr = cashInStr;
	}

	public String[] getCashOutStr() {
		return cashOutStr;
	}
	public void setCashOutStr(String[] cashOutStr) {
		this.cashOutStr = cashOutStr;
	}

	public String[] getLineNumStr() {
		return lineNumStr;
	}
	public void setLineNumStr(String[] lineNumStr) {
		this.lineNumStr = lineNumStr;
	}

	public ShiftTransDt getTrnDt() {
		return trnDt;
	}
	public void setTrnDt(ShiftTransDt trnDt) {
		this.trnDt = trnDt;
	}
	
}
